//串口服务器，连接tcp服务器
//实例化后调用newConnect
/*
传参{
    deviceId:'' , //设备ID
    com:'com1' , //串口号
    baudRate:9600 , //波特率
    ip : '127.0.0.1', //tcp服务器IP地址
    port : 15000 ,//端口号
}

*/
const net = require('net')
const SerialPort = require('serialport')

class SerialToTcp {
    constructor() {
        this.deviceIdPool = {}
        this.comPool = {}
    }


    connetTcp(config = {}) {
        config.ip = config.ip ? config.ip : '127.0.0.1'
        config.port = config.port?config.port : 15000
        const { ip, port, deviceId } = config
        if (this.deviceIdPool[deviceId]) {
            return this.deviceIdPool[deviceId]
        } else {
            const tcpClient = net.connect( port,ip, (err) =>{
                if(err)console.log(err);return});
            tcpClient.on('connect', () => {
                console.log(`连接${ip, port}成功`)
                //发送注册包
                tcpClient.write(Buffer.from(deviceId,'hex'))
            })
            this.deviceIdPool[deviceId] = tcpClient
            return tcpClient
        }


    }

    connectSerial(config = {}) {
        config.com = config.com ? config.com : 'com1'
        config.baudRate = config.baudRate ? config.baudRate : 9600
        const { com, baudRate } = config
        if (this.comPool[com]) {
            return this.comPool[com]
        } else {
            const serial = new SerialPort(com, baudRate)
            this.comPool[com] = serial
            return serial
        }

    }

    newConnect(config = {}) {
        config.com = config.com ? config.com : 'com1'
        config.baudRate = config.baudRate ? config.baudRate : 9600
        config.ip = config.ip ? config.ip : '127.0.0.1'
        config.port = config.port?config.port : 15000
        const tcpClient = this.connetTcp(config)
        const serial = this.connectSerial(config)

        tcpClient.on('data', (data) => {
            serial.write(data)
        })

        serial.on('data', (data) => {
            tcpClient.write(data)
        })
    }
}

module.exports = SerialToTcp